const db = require('../../db/sql')
const {delay} = require('../../utils/delay')

function addRole(params, res, role) {
    let name = params.role_name;
    let description = params.role_description;
    if (name == 'admin') {
        res.status(702).send({
            msg: "无法添加系统管理员"
        })
        return 0
    }
    if (role == '用户') {
        let findResult = params.permissions.find(o => o === 1 || o < 20)
        if (findResult) {
            res.sendStatus(407)
            return 0;
        }
    }
    //查询新增角色的英文识别名是否已经存在
    let sql1 = 'SELECT * FROM roles WHERE role_name = ?';
    db.query(sql1, [name], (err, results) => {
        if (err) {
            console.log(77)
            return res.status(500).send('Internal Server Error');
        }
        if (results.length > 0) {
            return res.status(409).send('Role name already exists');
        }
        //不存在则执行新增角色
        let sql2 = 'INSERT INTO roles (role_name, role_description) VALUES (?, ?)';
        db.query(sql2, [name, description], async (err, results) => {
            if (err) {
                console.log(err)
                return res.status(500).send('Internal Server Error');
            }
            let permissions = params.permissions;
            //然后根据权限的长度通过for循环依次插入对应权限
            // console.log('撒谎的',results.insertId)
            let insertId = results.insertId
            for (let i = 0; i < permissions.length; i++) {
                let sql3 = 'INSERT INTO role_permission (role_id, rank_id) VALUES (?, ?);';
                db.query(sql3, [results.insertId, permissions[i]], (err, results) => {
                    if (err) {
                        console.log(err);
                        return res.status(500).send('Internal Server Error');
                    }
                });
            }
            await delay(1200)
            //查询插入结果
            let sql4 = 'SELECT * FROM roles WHERE role_id = ?';
            db.query(sql4, [results.insertId], (err, results) => {
                if (err) {
                    console.log(err)
                    return res.status(500).send('Internal Server Error');
                }
                // console.log(results.insertId,'撒到')
                console.log(insertId, 'ids')
                return res.status(200).send({
                    id: insertId,
                    name,
                    description
                });
            });
        });
    });
}

module.exports = addRole
